import { useAppDispatch, useAppSelector } from "@/store";
import { fetchModifyPatientInforAction } from "@/store/modules/patient";
import {
  fetchAddProgrammeInfo,
  fetchGetProgrammeDetailInfo,
  fetchModifyProgrammeInfoAction,
} from "@/store/modules/programme";
import { Form, Input, Modal, Select } from "@arco-design/web-react";
import useForm from "@arco-design/web-react/es/Form/useForm";
import TextAreaRef from "@arco-design/web-react/es/Input/textarea";
import Item from "antd/es/list/Item";

import { memo, useEffect, useState, type FC } from "react";
const FormItem = Form.Item;
const Option = Select.Option;
interface IProps {
  getProgrammeList: () => void;
  SendCloseSelectedToSon: () => void;
  visible: boolean;
  handleVisible: (flag: boolean) => void;
  id: number | null;
  mode: "add" | "edit";
}
const ModifyAndAdd: FC<IProps> = ({
  SendCloseSelectedToSon,
  mode,
  visible,
  handleVisible,
  id,
  getProgrammeList,
}) => {
  const dispatch = useAppDispatch();
  const [form] = useForm();
  const { illnessList, examinationList, taskList } = useAppSelector(
    (state) => state.patient
  );
  const { detailInfo } = useAppSelector((state) => state.programme);
  const [programmeExaminationIds, setProgrammeExaminationIds] = useState<
    number[]
  >([]);
  const [modifyParams, setModifyParams] = useState<{
    title: string | null;
    content: string | null;
    illnessId: number;
  }>({ title: "", content: "", illnessId: 0 });
  const [programmeTaskIds, setProgrammeTaskIds] = useState<number[]>([]);
  useEffect(() => {
    if (mode === "edit") {
      dispatch(fetchGetProgrammeDetailInfo(id as number));
    }
  }, [dispatch, id, mode]);

  useEffect(() => {
    // console.log(examinationIds);
    if (detailInfo && mode === "edit") {
      const programmeExaminationIds = detailInfo?.programmeExaminations?.map(
        (item: any) => {
          return item.examinationId;
        }
      );
      const programmeTaskIds = detailInfo?.programmeTasks?.map(
        (item: any) => item.taskId
      );
      setProgrammeExaminationIds(programmeExaminationIds);
      setProgrammeTaskIds(programmeTaskIds);
      form.setFieldsValue({
        examinationName: programmeExaminationIds?.map(Number),
        taskName: programmeTaskIds?.map(Number),
        programmeTitle: detailInfo?.title,
        illnessName: detailInfo?.illnessId,
        programmeContent: detailInfo?.content,
      });
    }
    if (detailInfo && mode === "add") {
      form.resetFields();
    }
  }, [detailInfo, mode]);
  // console.log(programmeExaminationIds, programmeTaskIds);

  const forSureFn = async () => {
    if (id && mode === "edit") {
      const body = {
        content: modifyParams.content || null,
        createBy: detailInfo?.createBy || null,
        examinationIds: programmeExaminationIds,
        id: id,
        illnessId: modifyParams.illnessId,
        programmeExaminationList: [],
        programmeExaminations: detailInfo?.programmeExaminations,
        programmeTasks: detailInfo?.programmeTasks,
        taskIds: programmeTaskIds,
        title: modifyParams.title || null,
        updateBy: detailInfo?.updateBy,
        updateTime: detailInfo?.updateTime,
      };
      await dispatch(fetchModifyProgrammeInfoAction(body));
    }
    if (mode === "add") {
      const body = {
        content: modifyParams.content || null,
        createBy: null,
        creatTime: null,
        examinationIds: programmeExaminationIds,
        id: null,
        illnessId: modifyParams.illnessId,
        programmeExaminationList: [],
        taskIds: programmeTaskIds,
        title: modifyParams.title || null,
        updateBy: null,
        updateTime: null,
      };
      await dispatch(fetchAddProgrammeInfo(body));
    }
    getProgrammeList();
    handleVisible(false);
    SendCloseSelectedToSon();
  };

  return (
    <div>
      <Modal
        title={mode === "edit" ? "修改" : "新增"}
        visible={visible}
        onCancel={() => {
          SendCloseSelectedToSon();
          handleVisible(false);
        }}
        onOk={forSureFn}
      >
        <Form form={form}>
          <FormItem label="检查名称" field="examinationName">
            <Select
              mode="multiple"
              onChange={(item) => {
                setProgrammeExaminationIds(item);
              }}
              //   maxTagCount={{
              //     count: 5,
              //     render: (invisibleNumber) => `+${invisibleNumber} more`,
              //   }}
              placeholder="请输入检查名称"
              allowClear
            >
              {examinationList?.map((option) => (
                <Option key={option.id} value={option.id}>
                  {option.name}
                </Option>
              ))}
            </Select>
          </FormItem>
          <FormItem label="任务名称" field="taskName">
            <Select
              onChange={(item) => {
                setProgrammeTaskIds(item);
              }}
              mode="multiple"
              placeholder="请输入任务名称"
              allowClear
            >
              {taskList?.map((item) => {
                return (
                  <Option key={item.id} value={item.id}>
                    {item.title}
                  </Option>
                );
              })}
            </Select>
          </FormItem>
          <FormItem field="programmeTitle" label="方案标题">
            <Input
              placeholder="请输入方案标题"
              onChange={(item) => {
                setModifyParams((prev) => {
                  return { ...prev, title: item };
                });
              }}
            />
          </FormItem>
          <FormItem label="方案内容" field="programmeContent">
            <TextAreaRef
              placeholder="请输入方案内容"
              onChange={(item) =>
                setModifyParams((prev) => {
                  return {
                    ...prev,
                    content: item,
                  };
                })
              }
            ></TextAreaRef>
          </FormItem>
          <FormItem label="病种名称" field="illnessName">
            <Select
              allowClear
              placeholder="请输入病种名称"
              onChange={(id: number) => {
                setModifyParams((prev) => {
                  return { ...prev, illnessId: id };
                });
              }}
            >
              {illnessList?.map((item) => {
                return (
                  <Option key={item.id} value={item.id}>
                    {item.name}
                  </Option>
                );
              })}
            </Select>
          </FormItem>
        </Form>
      </Modal>
    </div>
  );
};
export default memo(ModifyAndAdd);
